﻿#include "smWeb.h"
#include "ui_smWeb.h"

smWeb::smWeb(QWidget *parent)
    : QMainWindow(parent)
{
    ui.setupUi(this);
    currentUrl = QString("http://baidu.com");
    QHBoxLayout* hlayout = new QHBoxLayout;

    currentView = new smallerWeb();
    hlayout->addWidget(currentView);
    ui.masterWidget->setLayout(hlayout);

    connect(currentView, &smallerWeb::urlChanged, this, &smWeb::changedUrl);
    currentView->setUrl(QUrl("http://baidu.com"));

}

void smWeb::changedUrl(const QUrl& url) {
    ui.urlEdit->setText(url.toString());
    currentUrl = url.toString();
}

void smWeb::goBack()     {
    ui.goBtn->setEnabled(false);
    if (currentView != NULL) {
        currentView->page()->triggerAction(QWebEnginePage::Back);
    }
    ui.goBtn->setEnabled(true);
}
void smWeb::goForward()  {
    ui.forwadBtn->setEnabled(false);
    if (currentView != NULL) {
        currentView->page()->triggerAction(QWebEnginePage::Forward);
    }
    ui.forwadBtn->setEnabled(true);
}
void smWeb::goHome()     {
    ui.homeBtn->setEnabled(false);
    if (currentUrl.isEmpty()) {
        currentUrl = QString("http://baidu.com");
    }
    currentView->setUrl(QUrl(currentUrl));
    ui.homeBtn->setEnabled(true);
}
void smWeb::goUrl() {
    ui.goBtn->setEnabled(false);
    if (ui.urlEdit->text().isEmpty()) return;
    
    currentUrl = ui.urlEdit->text();
    currentView->setUrl(QUrl(currentUrl));
    ui.goBtn->setEnabled(true);
}

void smWeb::goFlush() {
    ui.flushBtn->setEnabled(false);
    currentView->setUrl(QUrl(currentUrl));
    ui.flushBtn->setEnabled(true);
}
void smWeb::removeLayout(QWidget* wdialog, QLayout* layout) {
    wdialog->hide();
    QLayoutItem* child;
    if (layout == NULL)
        return;
    while ((child = layout->takeAt(0)) != NULL) {
        if (child->widget()) {
            child->widget()->setParent(NULL);
            delete child->widget();
        }
        else if (child->layout()) {
            removeLayout(NULL, child->layout());
        }
        delete child;
        child = NULL;
    }
    delete layout;
    layout = NULL;
}